package icedot.library.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * MD5 加密
 * @author LiQingQing 2012-08-10
 */
public class Md5 
{ 
	/***
	 * MD5加码 生成32位md5码
	 */
	public static String string2MD5(String str)
	{
		MessageDigest messageDigest = null;  
		  
        try 
        {  
            messageDigest = MessageDigest.getInstance("MD5");  
  
            messageDigest.reset();  
  
            messageDigest.update(str.getBytes("UTF-8"));  
        }
        catch (NoSuchAlgorithmException e) 
        {  
            System.out.println("NoSuchAlgorithmException caught!");  
            System.exit(-1);  
        } 
        catch (UnsupportedEncodingException e) 
        {  
            e.printStackTrace();  
        }  
  
        byte[] byteArray = messageDigest.digest();  
  
        StringBuffer md5StrBuff = new StringBuffer();  
  
        for (int i = 0; i < byteArray.length; i++) 
        {              
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
            else  
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));  
        }  
  
        return md5StrBuff.toString(); 
	}

	/**
	 * 加密解密算法 执行一次加密，两次解密
	 */ 
	public static String convertMD5(String inStr)
	{

		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++)
		{
			a[i] = (char) (a[i] ^ 't');
		}
		String s = new String(a);
		return s;
	}
	/**
	 *16位加密
	 * @param 加密前数据
	 * @return 加密后数据
	 */
	public static  String md5S16(String plainText) 
	{
		try 
		{		
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) 
			{
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString().substring(8,24);
			 
		} 
		catch (NoSuchAlgorithmException e) 
		{			
			return "";
		}
	} 

}